package com.huanglj.taobaounion.ui.fragment;



import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.huanglj.taobaounion.R;
import com.huanglj.taobaounion.base.BaseFragment;
import com.huanglj.taobaounion.model.domain.Categories;
import com.huanglj.taobaounion.model.domain.CategoriesById;
import com.huanglj.taobaounion.presenter.implement.HomePagerPresenterImpl;
import com.huanglj.taobaounion.presenter.implement.TicketPresenterImpl;
import com.huanglj.taobaounion.ui.activity.TicketActivity;
import com.huanglj.taobaounion.ui.adapter.HomePagerContentAdapter;
import com.huanglj.taobaounion.ui.adapter.LoopPagerAdapter;
import com.huanglj.taobaounion.utils.LogUtil;
import com.huanglj.taobaounion.utils.PresenterManager;
import com.huanglj.taobaounion.utils.SizeUtils;
import com.huanglj.taobaounion.view.IHomePagerCategoryById;
import com.huanglj.taobaounion.view.customView.LoadButtonView;
import com.huanglj.taobaounion.view.customView.LoopViewPager;
import com.lcodecore.tkrefreshlayout.utils.TbNestedScrollView;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.util.List;

import butterknife.BindView;

import static com.huanglj.taobaounion.utils.Contants.KEY_HOME_PAGER_ID;
import static com.huanglj.taobaounion.utils.Contants.KEY_HOME_PAGER_TITLE;


public class HomePagerFragment extends BaseFragment implements IHomePagerCategoryById {
    private static final String TAG = "HomePagerFragment";

    @BindView(R.id.page_recycler_view)
    RecyclerView mRecyclerView;

    @BindView(R.id.looper_pager)
    LoopViewPager mLooperPager;

    @BindView(R.id.home_pager_title)
    TextView mPagerTitle;
    @BindView(R.id.looper_point_container)
    LinearLayout mPointContainer;

    @BindView(R.id.refresh_layout)
    TwinklingRefreshLayout mRefreshLayout;

    @BindView(R.id.pager_nested_scroller)
    TbNestedScrollView mNestedScrollView;

    @BindView(R.id.home_pager_header)
    LinearLayout mPagerHeader;

    private HomePagerPresenterImpl mHomePagerPresenter;
    private Bundle mBundle;
    private String mTitle;
    private int mMaterialId;
    private HomePagerContentAdapter mAdapter;
    private LoopPagerAdapter mLoopPagerAdapter;
    private int mLoopSize;
    private GradientDrawable selectedDrawable;
    private GradientDrawable normalDrawable;
    private int mTargetItem;
    private LoadButtonView mBottomView;
    private final Context mContext;
    @BindView(R.id.home_pager)
    LinearLayout mHomePager;
    private int mHeightSize;

    public HomePagerFragment(Categories.DataBean dataBean) {
        Bundle bundle = new Bundle();
        bundle.putString(KEY_HOME_PAGER_TITLE,dataBean.getTitle());
        bundle.putInt(KEY_HOME_PAGER_ID,dataBean.getId());
        this.setArguments(bundle);
        mContext = getContext();
    }

    @Override
    protected void initPresenter() {
        mBundle = getArguments();
        mHomePagerPresenter = (HomePagerPresenterImpl) PresenterManager.getInstance().getHomePagerPresenter();
        mHomePagerPresenter.registerViewCallBack(this);

        mLoopPagerAdapter.setOnItemClickListener(new LoopPagerAdapter.OnItemClickListener() {
            @Override
            public void onClick(CategoriesById.DataBean item) {
                LogUtil.d(TAG,item.getTitle());
                handleItemClick(item);
            }
        });
        mAdapter.setOnItemClickListener(new HomePagerContentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(CategoriesById.DataBean item) {
                LogUtil.d(TAG,item.getTitle());
                handleItemClick(item);
            }
        });
    }

    private void handleItemClick(CategoriesById.DataBean item) {
        //跳转页面的同时加载数据
        TicketPresenterImpl ticketPresenter = (TicketPresenterImpl) PresenterManager.getInstance().getTicketPresenter();
        String coupon_click_url = item.getCoupon_click_url();
        if (TextUtils.isEmpty(coupon_click_url)){
            ticketPresenter.getTicket(item.getTitle(),item.getClick_url(),item.getPict_url());
        }else {
            ticketPresenter.getTicket(item.getTitle(),coupon_click_url,item.getPict_url());
        }
        LogUtil.d(TAG,"baseUrl--->"+item.getClick_url());
        startActivity(new Intent(getContext(),TicketActivity.class));
    }

    @Override
    public void onResume() {
        super.onResume();
        //可见的时候调用
        mLooperPager.startLooper();
    }

    @Override
    public void onPause() {
        super.onPause();
        mLooperPager.stopLooper();
    }


    @Override
    public int getRes() {
        return R.layout.fragment_home_pager;
    }

    @Override
    protected void loadData() {
        mMaterialId = mBundle.getInt(KEY_HOME_PAGER_ID);
        mHomePagerPresenter.getContentCategoryId(mMaterialId);
        mTitle = mBundle.getString(KEY_HOME_PAGER_TITLE);
        LogUtil.d(TAG,mTitle);
        if (mPagerTitle != null) {
            mPagerTitle.setText(mTitle);
        }
    }

    @Override
    protected void initView(View view) {
        //获取父控件尺寸
        /**
         * onCreateView方法中，控件没有加载完成，所以要用这种方式加载控件         */
        LogUtil.d(TAG,"homePager height: " + mHeightSize);
        if (mHomePager != null) {
            mHomePager.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (mHomePager == null) {
                        return;
                    }
                    int measuredHeight = mHomePager.getMeasuredHeight();
                    ViewGroup.LayoutParams layoutParams = mRecyclerView.getLayoutParams();
                    layoutParams.height = measuredHeight;
                    mRecyclerView.setLayoutParams(layoutParams);
                    //LogUtil.d(TAG,"homePager measureHeight: " + measuredHeight);

                    //获取ViewPager+标题的高度
                    int headerMeasuredHeight = mPagerHeader.getMeasuredHeight();
                    LogUtil.d(TAG,"header measureHeight: " + headerMeasuredHeight);
                    if (headerMeasuredHeight != 0) {
                        mNestedScrollView.setHanderHeight(headerMeasuredHeight);
                    }

                    if (measuredHeight != 0) {
                        mHomePager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            });
        }

        int measuredHeight = mHomePager.getMeasuredHeight();
        LogUtil.d(TAG,"homePager measureHeight:  " + measuredHeight);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, int itemPosition, @NonNull RecyclerView parent) {
                outRect.top = 8;
                outRect.bottom = 8;
            }
        });
        mAdapter = new HomePagerContentAdapter();
        mRecyclerView.setAdapter(mAdapter);

        mLoopPagerAdapter = new LoopPagerAdapter();
        mLooperPager.setAdapter(mLoopPagerAdapter);
        mLooperPager.setCurrentItem(Integer.MAX_VALUE/2);


        //给圆点指示器设置颜色
        selectedDrawable = (GradientDrawable) getContext().getResources().getDrawable(R.drawable.shape_point_container);
        selectedDrawable.setColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
        normalDrawable = (GradientDrawable) getContext().getResources().getDrawable(R.drawable.shape_point_container);
        normalDrawable.setColor(getContext().getResources().getColor(R.color.white));

        //设置相关的refresh
        initRefresh();
    }

    private void initRefresh() {
        mBottomView = new LoadButtonView(getContext());
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableOverScroll(false);
        mBottomView.setState(LoadButtonView.State.LOADING);
        mRefreshLayout.setBottomView(mBottomView);
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                mBottomView.setState(LoadButtonView.State.LOADING);
                mHomePagerPresenter.loadMore(mMaterialId);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mBottomView.getCurrentState() == LoadButtonView.State.LOADING) {
                            mRefreshLayout.finishLoadmore();
                        }
                    }
                },5000);
            }
        });
    }

    @Override
    protected void initListener() {
        mLooperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int realPosition = 0;
                if (mLoopSize!=0) {
                    realPosition = position % mLoopSize;
                }
                LogUtil.d(TAG,"currentPosition: " + realPosition);
                if (mPointContainer != null) {
                    for (int i = 0; i < mPointContainer.getChildCount(); i++) {
                        if (realPosition == i) {
                            mPointContainer.getChildAt(i).setBackground(selectedDrawable);
                        }else {
                            mPointContainer.getChildAt(i).setBackground(normalDrawable);
                        }
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @Override
    public void onContentLoaded(List<CategoriesById.DataBean> contents) {
        setUpState(State.SUCCESS);
        mAdapter.setData(contents);
    }

    @Override
    public int getCategoryId() {
        return mMaterialId;
    }

    @Override
    public void onLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onError(String msg) {
        setUpState(State.ERROR);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    public void onLoadMoreLoad(List<CategoriesById.DataBean> contents) {
        Toast.makeText(getContext(),"加载了" + contents.size()+"数据",Toast.LENGTH_SHORT).show();
        mAdapter.addData(contents);
        mRefreshLayout.finishLoadmore();
    }

    @Override
    public void onLoadMoreError() {
        mBottomView.setState(LoadButtonView.State.ERROR);
        mRefreshLayout.setBottomView(mBottomView);
    }

    @Override
    public void onLoadMoreEmpty() {
        mBottomView.setState(LoadButtonView.State.EMPTY);
        mRefreshLayout.setBottomView(mBottomView);
    }

    @Override
    public void onLoopLoad(List<CategoriesById.DataBean> contents) {
        mLoopSize = contents.size();
        LogUtil.d(TAG,"looper.size: "+ mLoopSize);
        //初始时需要设置圆点的颜色
        mTargetItem = (Integer.MAX_VALUE / 2) % mLoopSize;

        //创建适配器和配置适配器
        mLoopPagerAdapter.setData(contents);
        mPointContainer.removeAllViews();


        for (int i = 0; i < mLoopSize; i++) {
            View view = new View(getContext());
            int size = SizeUtils.dip2px(getContext(), 8);
            int marginSize = SizeUtils.dip2px(getContext(), 2);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size,size);
            params.setMargins(marginSize,0,marginSize,0);
            view.setLayoutParams(params);
            view.setBackground(normalDrawable);
            mPointContainer.addView(view);
        }
        //初始化的时候给第一个圆点设置值
        mPointContainer.getChildAt(mTargetItem).setBackground(selectedDrawable);
    }

    @Override
    public void onDestroy() {
        mHomePagerPresenter.unregisterViewCallBack(this);
        super.onDestroy();
    }
}
